package services
{
	import events.main.EventFilesSelect;
	
	import flash.events.Event;
	import flash.events.FileListEvent;
	import flash.filesystem.File;
	import flash.net.FileFilter;
	
	import org.robotlegs.mvcs.Actor;

	public class ServiceBrowseForFile extends Actor implements IServiceBrowseForFiles
	{
		private var file:File = File.desktopDirectory;
		
		
		public function ServiceBrowseForFile() : void {
			file.addEventListener(FileListEvent.SELECT_MULTIPLE, onSelect, false, 0, true);
			file.addEventListener(Event.SELECT, onSaveSelect, false, 0, true);
		}
		
		private function onSaveSelect(e:Event) : void {
			var files:Array = new Array();
			files.push(file.nativePath);
			dispatch(new EventFilesSelect(EventFilesSelect.FILES_SELECT, files));
		}
		
		private function onSelect(e:FileListEvent) : void {
			var files:Array = new Array();
			var i:uint;
			for (i = 0; i < e.files.length; i++) {
				files.push(File(e.files[i]).nativePath);
			}
			dispatch(new EventFilesSelect(EventFilesSelect.FILES_SELECT, files));
		}
		
		public function browseForOpenMultiple(...extensions):void
		{
			file.browseForOpenMultiple("Select Files:", getFilters(extensions)); 
		}
		
		public function browseForOpen(...extensions) : void {
			var fileFilter:Array = new Array();
			file.browseForOpen("Select File:", getFilters(extensions));
		}
		
		public function browseForSave(fileName:String) : void {
			var fileFilter:Array = new Array();
			file.nativePath = File.documentsDirectory.nativePath + File.separator + fileName;
			file.browseForSave("Save As:");
			
		}
		
		private function getFilters(extensions:Array=null) : Array {
			if (extensions != null && extensions.length > 0){
				var filters:Array = new Array();
				var i:uint;
				for (i = 0; i < extensions.length; i++){
					var filter:FileFilter = new FileFilter(extensions[i][0]+"", (extensions[i] as Array).slice(1).join(";"));
					filters.push(filter);
				}
				return filters;
			}
			return null;
		}
	}
}